package com.viknix.threadpool.manager.client.template;

import com.viknix.threadpool.manager.client.alertor.AlertParam;
import com.viknix.threadpool.manager.client.builder.ThreadPoolBuilder;
import com.viknix.threadpool.manager.client.core.DynamicThreadPoolExecutor;
import com.viknix.threadpool.manager.client.factory.BlockingQueueFactory;
import com.viknix.threadpool.manager.client.factory.RejectedHandlerFactory;
import com.viknix.threadpool.manager.client.util.ValidatorUtil;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: Dongqi
 * @Date: 2021/11/22 09:59
 * @Version 1.0
 * @Description: 动态线程池模板工具
 */
public class DynamicThreadPoolExecutorTemplate extends AbstractThreadPoolExecutorTemplate {

    private static volatile DynamicThreadPoolExecutorTemplate instance;

    private DynamicThreadPoolExecutorTemplate() {
    }

    public static synchronized DynamicThreadPoolExecutorTemplate getInstance() {
        if (instance == null) {
            synchronized (DynamicThreadPoolExecutorTemplate.class) {
                if (instance == null) {
                    instance = new DynamicThreadPoolExecutorTemplate();
                }
            }
        }
        return instance;
    }

    @Override
    protected ThreadPoolExecutor buildThreadPoolExecutor(ThreadPoolBuilder builder) {
        AlertParam alertorParam = new AlertParam(
                builder.isAlert(),
                builder.getLivenessAlert(),
                builder.getCapacityAlert());
        return new DynamicThreadPoolExecutor(
                builder.getCorePoolSize(),
                builder.getMaxPoolSize(),
                builder.getKeepAliveTime(),
                builder.getTimeUnit(),
                BlockingQueueFactory.createBlockingQueue(builder.getBlockingQueueCode(), builder.getCapacity()),
                builder.getThreadFactory(),
                RejectedHandlerFactory.createPolicy(builder.getRejectedHandlerCode()),
                builder.getThreadPoolId(),
                alertorParam);
    }
}
